<template>
  <div class="domain-reverse-check-container">
    <!-- 顶部栏与侧边栏将由MainHeader和SideMenu组件提供 -->
    <MainHeader/>

    <div class="main-container">
      <!-- 左侧导航 -->
      <SideMenu/>

      <!-- 主内容区域 -->
      <div class="content-container">
        <div class="search-content">
          <div class="page-header">
            <div class="title">{{ t('domain.reverse.title') }}</div>
            <div class="description">
              {{ t('domain.reverse.description') }}
            </div>
          </div>

          <div class="search-box">
            <el-input
                :placeholder="t('domain.reverse.search.placeholder')"
                v-model="searchDomain"
                class="search-input"
                clearable
                @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon>
                  <Search/>
                </el-icon>
              </template>
            </el-input>

            <el-button type="primary" class="search-button" @click="handleSearch">{{
                t('domain.reverse.search.button')
              }}
            </el-button>
            <el-button type="success" class="action-button batch-search-btn" @click="showBatchDialog = true">
              <el-icon :size="18"><Upload /></el-icon>
              {{ getCurrentLanguage() === 'zh' ? '批量反查' : 'Batch Reverse' }}
            </el-button>
          </div>

          <!-- API错误信息 -->
          <div v-if="apiError" class="api-error-alert">
            <el-alert
                type="error"
                :description="`请求失败: ${apiError}。`"
                show-icon
                closable
            />
          </div>

          <!-- 搜索结果区域 -->
          <div class="search-results" v-if="searchResults.length">
            <div class="results-header">
              <h3>{{ t('domain.reverse.results') }} ({{ searchResults.length }}条)</h3>
              <el-button size="small" @click="clearResults">{{ t('domain.reverse.return') }}</el-button>
            </div>

            <div class="result-cards">
              <div v-for="(result, index) in searchResults" :key="index" class="result-card">
                <div class="result-header">
                  <h4>{{
                      result.name || result.company_name || result.Full_name ||
                      result.exhibitor_name || result.Company_Name || t('domain.reverse.unknown')
                    }}</h4>
                  <div class="result-source">{{ getSourceName(result.source) }}</div>
                </div>

                <div class="result-content">
                  <!-- 展示所有非空字段 -->
                  <template v-for="(value, key) in getFilteredFields(result)" :key="key">
                    <div class="info-row">
                      <span class="info-label">{{ getFieldLabel(key) }}:</span>
                      <span class="info-value" :class="{ highlight: isHighlightField(key) }">
                        {{ value }}
                      </span>
                      <el-button v-if="isHighlightField(key)"
                                 size="small"
                                 @click="copyToClipboard(value)"
                                 class="copy-btn">{{ t('domain.reverse.copy') }}
                      </el-button>
                    </div>
                  </template>
                </div>
              </div>
            </div>

            <!-- 加载更多按钮 -->
            <div class="load-more" v-if="searchResults.length < totalResults">
              <el-button type="primary" plain @click="loadMore" :loading="loading">{{
                  t('domain.reverse.load.more')
                }}
              </el-button>
            </div>
          </div>

          <!-- 无搜索结果 -->
          <div class="no-results" v-if="searched && !searchResults.length && !apiError">
            <el-empty :description="t('domain.reverse.no.results')"></el-empty>
          </div>

          <!-- 加载状态 -->
          <div class="loading-container" v-if="loading">
            <el-skeleton :rows="5" animated/>
          </div>

          <!-- 功能介绍卡片，仅在没有搜索结果且未搜索时显示 -->
          <div class="feature-cards" v-if="!searchResults.length && !searched">
            <div class="feature-card">
              <div class="icon">
                <el-icon :size="40" class="blue-icon">
                  <Link/>
                </el-icon>
              </div>
              <div class="card-content">
                <div class="card-title">{{ t('domain.reverse.feature.domain') }}</div>
                <div class="card-desc">{{ t('domain.reverse.feature.domain.desc') }}</div>
              </div>
            </div>

            <div class="feature-card">
              <div class="icon">
                <el-icon :size="40" class="green-icon">
                  <Search/>
                </el-icon>
              </div>
              <div class="card-content">
                <div class="card-title">{{ t('domain.reverse.feature.precision') }}</div>
                <div class="card-desc">{{ t('domain.reverse.feature.precision.desc') }}</div>
              </div>
            </div>

            <div class="feature-card">
              <div class="icon">
                <el-icon :size="40" class="purple-icon">
                  <DataLine/>
                </el-icon>
              </div>
              <div class="card-content">
                <div class="card-title">{{ t('domain.reverse.feature.multi.source') }}</div>
                <div class="card-desc">{{ t('domain.reverse.feature.multi.source.desc') }}</div>
              </div>
            </div>

            <div class="feature-card">
              <div class="icon">
                <el-icon :size="40" class="orange-icon">
                  <CopyDocument/>
                </el-icon>
              </div>
              <div class="card-content">
                <div class="card-title">{{ t('domain.reverse.feature.export') }}</div>
                <div class="card-desc">{{ t('domain.reverse.feature.export.desc') }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 批量反查对话框 -->
    <el-dialog
      v-model="showBatchDialog"
      :title="getCurrentLanguage() === 'zh' ? '批量域名反查' : 'Batch Domain Reverse Check'"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="batch-dialog-content">
        
        <el-alert
          :title="getCurrentLanguage() === 'zh' ? '使用说明' : 'Instructions'"
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        >
          <template #default>
            <div v-if="getCurrentLanguage() === 'zh'">
              <p>1. 请上传包含Domain（域名）、Website（网址）或Website（网站）列的Excel文件</p>
              <p>2. 系统将自动识别表头中的域名列并进行反查</p>
              <p>3. 系统将在4个数据源中搜索匹配数据：LinkedIn、全球企业库、广交会采购商、广交会展商</p>
              <p>4. 搜索结果将自动下载为Excel文件，每个数据源对应一个工作表</p>
              <p>5. 只有包含数据的数据源才会生成工作表，无数据的数据源会自动跳过</p>
            </div>
            <div v-else>
              <p>1. Please upload an Excel file with a Domain, Website, or URL column</p>
              <p>2. The system will automatically identify the domain column and perform reverse lookup</p>
              <p>3. The system will search 4 data sources: LinkedIn, Global Enterprise, Canton Fair Buyers, Canton Fair Exhibitors</p>
              <p>4. Results will be automatically downloaded as an Excel file with separate sheets for each data source</p>
              <p>5. Only data sources with results will generate worksheets, empty sources will be skipped</p>
            </div>
          </template>
        </el-alert>
        
        <!-- 文件上传 -->
        <el-upload
          ref="uploadRef"
          class="upload-demo"
          drag
          :auto-upload="false"
          :limit="1"
          :on-change="handleFileChange"
          :on-exceed="handleExceed"
          accept=".xlsx,.xls"
          :file-list="fileList"
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            {{ getCurrentLanguage() === 'zh' ? '将Excel文件拖到此处，或' : 'Drop Excel file here or' }}
            <em>{{ getCurrentLanguage() === 'zh' ? '点击上传' : 'click to upload' }}</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              {{ getCurrentLanguage() === 'zh' ? '仅支持 .xlsx 和 .xls 格式的文件' : 'Only .xlsx and .xls files are supported' }}
            </div>
          </template>
        </el-upload>
        
        <!-- 进度条 -->
        <div v-if="batchUploading" style="margin-top: 20px;">
          <el-progress :percentage="uploadProgress" :status="uploadStatus"></el-progress>
          <div style="text-align: center; margin-top: 10px; color: #606266;">
            {{ uploadStatusText }}
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button type="warning" plain @click="downloadTemplate">
            <el-icon><Download /></el-icon>
            {{ getCurrentLanguage() === 'zh' ? '下载Excel模板' : 'Excel Template' }}
          </el-button>

          <el-button @click="cancelBatchUpload">
            {{ getCurrentLanguage() === 'zh' ? '取消' : 'Cancel' }}
          </el-button>
          <el-button
            type="primary"
            @click="submitBatchReverse"
            :loading="batchUploading"
            :disabled="!selectedFile"
          >
            {{ getCurrentLanguage() === 'zh' ? '开始反查' : 'Start Reverse' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, computed} from 'vue'
import {Search, Link, DataLine, CopyDocument, Upload, UploadFilled, Download} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'
import axios from 'axios'
import MainHeader from '@/components/MainHeader.vue'
import SideMenu from '@/components/SideMenu.vue'
import {useRouter} from 'vue-router'
import {t} from '@/utils/i18n'
import {getCurrentLanguage} from "../utils/i18n";

// 定义响应式数据
const searchDomain = ref('')
const searchResults = ref([])
const loading = ref(false)
const searched = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalResults = ref(0)
const apiError = ref(null)
const router = useRouter()

// 批量反查相关数据
const showBatchDialog = ref(false)
const selectedFile = ref(null)
const fileList = ref([])
const uploadRef = ref(null)
const batchUploading = ref(false)
const uploadProgress = ref(0)
const uploadStatus = ref('')
const uploadStatusText = ref('')

// 判断是否为需要高亮的字段
const isHighlightField = (key) => {
  const highlightFields = [
    'email', 'Emails', 'phone', 'Phone_numbers', 'mobile_phone', 'telephone',
    'website', 'web_address', 'url', 'web_url', 'domain', 'website_url',
    'Company_Website', 'company_website', 'company_domain'
  ];
  return highlightFields.includes(key);
};

// 实际搜索函数
const handleSearch = async () => {
  if (!searchDomain.value.trim()) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('请输入域名')
    } else {
      ElMessage.warning('Please enter a domain')
    }
    return
  }

  // 检查是否有token
  const token = localStorage.getItem('token')
  if (!token) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('您尚未登录，请先登录后再进行查询')
    } else {
      ElMessage.warning('You are not logged in, please log in first before searching')
    }
    // 保存当前路径用于登录后重定向
    localStorage.setItem('redirectPath', '/domain-reverse-check')
    // 跳转到登录页
    router.push('/login')
    return
  }

  // 统计真实搜索次数
  let count = parseInt(localStorage.getItem('searchCount_domainReverse') || '0')
  localStorage.setItem('searchCount_domainReverse', count + 1)

  loading.value = true
  searched.value = true
  currentPage.value = 1
  apiError.value = null

  try {
    const response = await axios.get('/api/domain-lookup', {
      params: {
        domain: searchDomain.value,
        page: currentPage.value,
        size: pageSize.value
      },
      headers: {
        'Authorization': `Bearer ${token}`  // 确保请求携带token
      },
      // 添加超时设置
      timeout: 60000 // 域名查询需要更长的超时时间
    });

    if (response.data && typeof response.data === 'object') {
      searchResults.value = response.data.results || [];
      totalResults.value = response.data.total || 0;

      // 检查是否返回了错误信息
      if (response.data.error) {
        apiError.value = response.data.error;
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error(`搜索出现错误: ${response.data.error}`);
        } else {
          ElMessage.error(`Search failed`);
        }
      }
    } else {
      apiError.value = '服务器返回的数据格式不正确';
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('服务器返回的数据格式不正确');
      } else {
        ElMessage.error('Server returned data in an incorrect format');
      }
      searchResults.value = [];
      totalResults.value = 0;
    }
  } catch (error) {

    // 详细的错误处理
    if (error.response) {
      // 服务器返回了错误状态码
      const status = error.response.status;
      apiError.value = `服务器返回错误(${status}): ${error.response.data?.message || error.message || '未知错误'}`;
    } else if (error.request) {
      // 请求已发出，但没有收到响应
      apiError.value = '服务器未响应，请检查后端服务是否正常运行';
    } else {
      // 请求设置触发的错误
      apiError.value = `请求错误: ${error.message}`;
    }
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error(`搜索失败: ${apiError.value}`);
    } else {
      ElMessage.error(`Search failed`);
    }
    searchResults.value = [];
    totalResults.value = 0;
  } finally {
    loading.value = false;
  }
};

// 加载更多结果
const loadMore = async () => {
  if (searchResults.value.length >= totalResults.value) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.info('已加载全部数据');
    } else {
      ElMessage.info('All data has been loaded');
    }
    return;
  }

  // 获取token
  const token = localStorage.getItem('token')
  if (!token) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('您的登录已过期，请重新登录')
    } else {
      ElMessage.warning('Your login has expired, please log in again')
    }
    router.push('/login')
    return
  }

  loading.value = true;
  currentPage.value += 1;

  try {
    const response = await axios.get('/api/domain-lookup', {
      params: {
        domain: searchDomain.value,
        page: currentPage.value,
        size: pageSize.value
      },
      headers: {
        'Authorization': `Bearer ${token}`  // 确保请求携带token
      }
    });

    const newResults = response.data.results || [];
    searchResults.value = [...searchResults.value, ...newResults];
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error(`加载更多失败: ${error.message || '服务器连接失败'}`);
    } else {
      ElMessage.error(`Failed to load more`);
    }
    currentPage.value -= 1;
  } finally {
    loading.value = false;
  }
};

// 清除搜索结果
const clearResults = () => {
  searchResults.value = [];
  searched.value = false;
  currentPage.value = 1;
  totalResults.value = 0;
  apiError.value = null;
};

// 复制到剪贴板
const copyToClipboard = (text) => {
  navigator.clipboard.writeText(text)
      .then(() => {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.success('已复制到剪贴板');
        } else {
          ElMessage.success('Copied to clipboard');
        }
      })
      .catch(() => {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error('复制失败，请手动复制');
        } else {
          ElMessage.error('Copy failed, please manually copy');
        }
      });
};

// 获取数据源名称
const getSourceName = (source) => {
  const sourceMap = {
    'canton_fair_exhibitors': t('domain.reverse.source.canton.exhibitor'),
    'canton_fair_buyers': t('domain.reverse.source.canton.buyer'),
    'facebook_data': t('domain.reverse.source.facebook'),
    'global_enterprise_library': t('domain.reverse.source.enterprise'),
    'linkedin_data': t('domain.reverse.source.linkedin'),
    'twitter_data': t('domain.reverse.source.twitter'),
    'customs_trade': t('domain.reverse.source.customs')
  };
  return sourceMap[source] || t('domain.reverse.source.unknown');
};

// 过滤掉空字段和source字段
const getFilteredFields = (result) => {
  const filteredObj = {};

  // 字段名映射关系，解决中英文混合的问题
  const fieldNameMapping = {
    // 中文字段名转为标准小写英文
    '部门': 'department',
    '公司name': 'companyname',
    '公司域名': 'companydomain',
    '公司phone': 'companyphone',
    '公司industry': 'companyindustry',
    '公司sic编码': 'companysiccode',
    '公司地址': 'companyaddress',
    '公司city': 'companycity',
    '公司state': 'companystate',
    '公司zip': 'companyzip',
    '公司领英网址': 'companylinkedinurl',
    '公司revenue': 'companyrevenue',
    '公司employeecount': 'companyemployeecount',
    '领英网址': 'linkedinurl',
    'import时间': 'importtime'
  };

  // 需要过滤掉的字段列表
  const excludeFields = [
    'import_error', 'import_status', 'import_time', 'BUSINESS_EMAIL_VALIDATION_STATUS', 'last_updated'
  ];

  Object.entries(result).forEach(([key, value]) => {
    if (value !== null && value !== undefined && value !== '' && key !== 'source') {
      // 标准化字段名
      let normalizedKey = key;

      // 如果字段名在映射表中，使用标准化的英文字段名
      if (fieldNameMapping[key]) {
        normalizedKey = fieldNameMapping[key];
      }

      // 检查是否为需要过滤的字段
      if (!excludeFields.includes(normalizedKey) && !excludeFields.includes(key)) {
        // 存储标准化后的字段和值
        filteredObj[normalizedKey] = value;
      }
    }
  });

  return filteredObj;
};

// 获取字段名称的标签，根据当前语言环境显示中文或英文
const getFieldLabel = (key) => {
  // 检测当前语言 - 修复语言检测逻辑
  const currentLang = localStorage.getItem('APP_LANGUAGE') || 'zh';
  const isEnglish = currentLang === 'en';

  // 字段名映射表
  const fieldLabels = {
    // 基本字段
    'id': {'zh': '编号', 'en': 'ID'},
    'firstname': {'zh': '名', 'en': 'First Name'},
    'FIRST_NAME': {'zh': '名', 'en': 'First Name'},
    'middlename': {'zh': '中间名', 'en': 'Middle Name'},
    'lastname': {'zh': '姓', 'en': 'Last Name'},
    'LAST_NAME': {'zh': '姓', 'en': 'Last Name'},
    'businessemail': {'zh': '公司邮箱', 'en': 'Business Email'},
    'BUSINESS_EMAIL': {'zh': '公司邮箱', 'en': 'Business Email'},
    'personalemails': {'zh': '个人邮箱', 'en': 'Personal Emails'},
    'PERSONAL_EMAILS': {'zh': '个人邮箱', 'en': 'Personal Emails'},
    'jobtitle': {'zh': '职位', 'en': 'Job Title'},
    'JOB_TITLE': {'zh': '职位', 'en': 'Job Title'},
    'senioritylevel': {'zh': '资历', 'en': 'Seniority Level'},
    'SENIORITY_LEVEL': {'zh': '资历', 'en': 'Seniority Level'},
    'department': {'zh': '部门', 'en': 'Department'},
    'DEPARTMENT': {'zh': '部门', 'en': 'Department'},
    'mobilephone': {'zh': '手机', 'en': 'Mobile Phone'},
    'MOBILE_PHONE': {'zh': '手机', 'en': 'Mobile Phone'},
    'contactmetrocity': {'zh': '联系城市', 'en': 'Contact Metro City'},
    'contactstate': {'zh': '联系州', 'en': 'Contact State'},

    // 公司相关字段
    'companyname': {'zh': '公司名称', 'en': 'Company Name'},
    'COMPANY_NAME': {'zh': '公司名称', 'en': 'Company Name'},
    'companydomain': {'zh': '公司域名', 'en': 'Company Domain'},
    'COMPANY_DOMAIN': {'zh': '公司域名', 'en': 'Company Domain'},
    'companyphone': {'zh': '公司电话', 'en': 'Company Phone'},
    'COMPANY_PHONE': {'zh': '公司电话', 'en': 'Company Phone'},
    'primaryindustry': {'zh': '主要行业', 'en': 'Primary Industry'},
    'PRIMARY_INDUSTRY': {'zh': '主要行业', 'en': 'Primary Industry'},
    'CONTACT_METRO_CITY': {'zh': '联系城市', 'en': 'Contact Metro City'},
    'CONTACT_STATE': {'zh': '联系州', 'en': 'Contact State'},
    'primarysic': {'zh': '主要SIC', 'en': 'Primary SIC'},
    'PRIMARY_SIC': {'zh': '主要SIC', 'en': 'Primary SIC'},
    'companyindustry': {'zh': '公司行业', 'en': 'Company Industry'},
    'COMPANY_INDUSTRY': {'zh': '公司行业', 'en': 'Company Industry'},
    'companysiccode': {'zh': '公司SIC编码', 'en': 'Company SIC Code'},
    'COMPANY_SIC_CODE': {'zh': '公司SIC编码', 'en': 'Company SIC Code'},
    'companyaddress': {'zh': '公司地址', 'en': 'Company Address'},
    'COMPANY_ADDRESS': {'zh': '公司地址', 'en': 'Company Address'},
    'companycity': {'zh': '公司城市', 'en': 'Company City'},
    'COMPANY_CITY': {'zh': '公司城市', 'en': 'Company City'},
    'companystate': {'zh': '公司州', 'en': 'Company State'},
    'COMPANY_STATE': {'zh': '公司州', 'en': 'Company State'},
    'companyzip': {'zh': '公司邮编', 'en': 'Company ZIP'},
    'COMPANY_ZIP': {'zh': '公司邮编', 'en': 'Company ZIP'},
    'companylinkedinurl': {'zh': '公司领英网址', 'en': 'Company LinkedIn URL'},
    'COMPANY_LINKEDIN_URL': {'zh': '公司领英网址', 'en': 'Company LinkedIn URL'},
    'companyrevenue': {'zh': '公司收入', 'en': 'Company Revenue'},
    'COMPANY_REVENUE': {'zh': '公司收入', 'en': 'Company Revenue'},
    'companyemployeecount': {'zh': '公司规模', 'en': 'Company Employee Count'},
    'COMPANY_EMPLOYEE_COUNT': {'zh': '公司规模', 'en': 'Company Employee Count'},

    // LinkedIn相关
    'linkedinurl': {'zh': '领英网址', 'en': 'LinkedIn URL'},
    'LINKEDIN_URL': {'zh': '领英网址', 'en': 'LinkedIn URL'},

    // 广交会采购商
    'country_region': {'zh': '国家/地区', 'en': 'Country/Region'},
    'procurement_product_type': {'zh': '采购产品类型', 'en': 'Procurement Product Type'},
    'contact_team': {'zh': '联系团队', 'en': 'Contact Team'},
    'contact_way': {'zh': '联系方式', 'en': 'Contact Method'},

    // 广交会参展商
    'exhibitor_name': {'zh': '展商名称', 'en': 'Exhibitor Name'},
    'booth_number': {'zh': '展位号', 'en': 'Booth Number'},
    'contact_person': {'zh': '联系人', 'en': 'Contact Person'},
    'mobile_phone': {'zh': '手机', 'en': 'Mobile Phone'},
    'telephone': {'zh': '电话', 'en': 'Telephone'},
    'province': {'zh': '省份', 'en': 'Province'},
    'city': {'zh': '城市', 'en': 'City'},
    'postal_code': {'zh': '邮编', 'en': 'Postal Code'},
    'main_products': {'zh': '主营产品', 'en': 'Main Products'},
    'main_keywords': {'zh': '主营关键词', 'en': 'Main Keywords'},
    'establishment_year': {'zh': '成立时间', 'en': 'Establishment Year'},
    'registered_capital': {'zh': '注册资金', 'en': 'Registered Capital'},
    'enterprise_scale': {'zh': '企业规模', 'en': 'Enterprise Scale'},
    'enterprise_type': {'zh': '企业类型', 'en': 'Enterprise Type'},
    'trade_form': {'zh': '贸易形式', 'en': 'Trade Form'},
    'exhibition_history': {'zh': '参展历史', 'en': 'Exhibition History'},
    'enterprise_nature': {'zh': '企业性质', 'en': 'Enterprise Nature'},
    'email_address': {'zh': '电子邮箱', 'en': 'Email Address'},
    'fax': {'zh': '传真', 'en': 'Fax'},
    'website': {'zh': '官网', 'en': 'Website'},
    'product': {'zh': '产品', 'en': 'Product'},
    'address': {'zh': '地址', 'en': 'Address'},
    'session': {'zh': '届数', 'en': 'Session'},

    // LinkedIn数据
    'full_name': {'zh': '全名', 'en': 'Full Name'},
    'Full_name': {'zh': '全名', 'en': 'Full Name'},
    'Industry': {'zh': '行业', 'en': 'Industry'},
    'industry': {'zh': '行业', 'en': 'Industry'},
    'Job_title': {'zh': '职位头衔', 'en': 'Job Title'},
    'Sub_Role': {'zh': '子角色', 'en': 'Sub Role'},
    'industry2': {'zh': '子行业', 'en': 'Industry 2'},
    'Emails': {'zh': '邮箱', 'en': 'Emails'},
    'email': {'zh': '邮箱', 'en': 'Email'},
    'Mobile': {'zh': '手机', 'en': 'Mobile'},
    'Phone_numbers': {'zh': '电话号码', 'en': 'Phone Numbers'},
    'phone': {'zh': '电话', 'en': 'Phone'},
    'Company_Name': {'zh': '公司名称', 'en': 'Company Name'},
    'company_name': {'zh': '公司名称', 'en': 'Company Name'},
    'Company_Industry': {'zh': '公司行业', 'en': 'Company Industry'},
    'Company_Website': {'zh': '公司网站', 'en': 'Company Website'},
    'Company_Size': {'zh': '公司规模', 'en': 'Company Size'},
    'Company_Founded': {'zh': '公司成立年份', 'en': 'Company Founded'},
    'Location': {'zh': '位置', 'en': 'Location'},
    'locality': {'zh': '位置', 'en': 'Location'},
    'metro': {'zh': '地铁', 'en': 'Metro'},
    'region': {'zh': '地区', 'en': 'Region'},
    'Skills': {'zh': '技能', 'en': 'Skills'},
    'First_Name': {'zh': '名', 'en': 'First Name'},
    'first_name': {'zh': '名', 'en': 'First Name'},
    'Middle_Initial': {'zh': '中间名首字母', 'en': 'Middle Initial'},
    'Middle_Name': {'zh': '中间名', 'en': 'Middle Name'},
    'middle_name': {'zh': '中间名', 'en': 'Middle Name'},
    'Last_Name': {'zh': '姓', 'en': 'Last Name'},
    'last_name': {'zh': '姓', 'en': 'Last Name'},
    'Gender': {'zh': '性别', 'en': 'Gender'},
    'gender': {'zh': '性别', 'en': 'Gender'},
    'LinkedIn_Url': {'zh': '领英网址', 'en': 'LinkedIn URL'},
    'facebook_url': {'zh': 'facebook网址', 'en': 'Facebook URL'},
    'linkedin_user_name': {'zh': '领英用户名', 'en': 'LinkedIn Username'},
    'company_location_address_line2': {'zh': '公司地理位置', 'en': 'Company Location Address'},
    'company_location_continent': {'zh': '公司位置大洲', 'en': 'Company Location Continent'},
    'company_location_country': {'zh': '公司所在国家', 'en': 'Company Location Country'},
    'company_location_geo': {'zh': '公司经纬度位置', 'en': 'Company Location Geo'},
    'company_location_locality': {'zh': '公司本地化', 'en': 'Company Location Locality'},
    'company_location_metro': {'zh': '公司位置地铁', 'en': 'Company Location Metro'},
    'company_location_name': {'zh': '公司位置名称', 'en': 'Company Location Name'},
    'company_location_postal_code': {'zh': '公司邮编', 'en': 'Company Location Postal Code'},
    'company_location_region': {'zh': '公司所在区域', 'en': 'Company Location Region'},
    'company_location_street_address': {'zh': '公司所在街道位置', 'en': 'Company Location Street Address'},
    'company_size': {'zh': '公司员工规模', 'en': 'Company Size'},
    'company_twitter_url': {'zh': '公司推特网址', 'en': 'Company Twitter Url'},
    'countries': {'zh': '国家', 'en': 'Countries'},
    'emails': {'zh': '邮箱', 'en': 'Email'},
    'github_url': {'zh': 'github网址', 'en': 'Github Url'},
    'github_user_name': {'zh': 'github用户名', 'en': 'Github Username'},
    'inferred_salary': {'zh': '工资', 'en': 'Inferred Salary'},
    'interests': {'zh': '利益', 'en': 'Interests'},
    'job_summary': {'zh': '工作总结', 'en': 'Job Summary'},
    'job_title': {'zh': '职位', 'en': 'Job Title'},
    'linkedin_connections': {'zh': '领英连接', 'en': 'Linked Connections'},
    'linkedin_url': {'zh': '领英网址', 'en': 'Linkedin Url'},
    'location_country': {'zh': '国家', 'en': 'Location Country'},
    'location_geo': {'zh': '地理经纬度', 'en': 'Location Geo'},
    'mobile': {'zh': '手机', 'en': 'Mobile'},
    'phone_numbers': {'zh': '手机号码', 'en': 'Phone Numbers'},
    'skills': {'zh': '技能', 'en': 'Skills'},
    'start_date': {'zh': '开始日期', 'en': 'Start Date'},
    'street_address': {'zh': '街道位置', 'en': 'Street Address'},
    'sub_role': {'zh': '子角色', 'en': 'Sub Role'},
    'summary': {'zh': '摘要', 'en': 'Summary'},
    'twitter_url': {'zh': '推特网址', 'en': 'Twitter Url'},
    'twitter_user_name': {'zh': '推特用户名', 'en': 'Twitter Username'},
    'years_experience': {'zh': '工作经验', 'en': 'Years Experience'},

    // Facebook数据
    'facebook_user_name': {'zh': 'facebook用户名', 'en': 'Facebook Username'},
    'snapchat_username': {'zh': 'Snapchat用户名', 'en': 'Snapchat Username'},
    'dob': {'zh': '出生日期', 'en': 'Date of Birth'},
    'location': {'zh': '位置', 'en': 'Location'},

    // 通用
    'position': {'zh': '职位', 'en': 'Position'},
    'name': {'zh': '姓名', 'en': 'Name'},
    'domain': {'zh': '域名', 'en': 'Domain'},
    'url': {'zh': 'URL地址', 'en': 'URL'},
    'web_url': {'zh': '网址', 'en': 'Web URL'},
    'web_address': {'zh': '网站', 'en': 'Web Address'},
    'website_url': {'zh': '网站地址', 'en': 'Website URL'},
    'company_website': {'zh': '公司网站', 'en': 'Company Website'},
    'company_domain': {'zh': '公司域名', 'en': 'Company Domain'}
  };

  // 先尝试在映射表中查找
  const lowerKey = key.toLowerCase();
  for (const [mapKey, labels] of Object.entries(fieldLabels)) {
    if (mapKey.toLowerCase() === lowerKey || key === mapKey) {
      return isEnglish ? labels['en'] : labels['zh'];
    }
  }

  // 处理未映射的字段
  if (isEnglish) {
    // 对于英文环境，将字段名格式化为友好的显示形式
    if (key.includes('_')) {
      // 下划线格式转为空格分隔，并将首字母大写
      return key.split('_')
          .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
          .join(' ');
    } else if (/[A-Z]/.test(key)) {
      // 驼峰格式转为空格分隔，并将首字母大写
      return key.replace(/([A-Z])/g, ' $1')
          .trim()
          .split(' ')
          .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
          .join(' ');
    }
    return key.charAt(0).toUpperCase() + key.slice(1); // 首字母大写
  } else {
    // 对于中文环境，尝试将英文转为中文
    let words = key.split('_');
    if (words.length === 1 && /[A-Z]/.test(key)) {
      // 处理驼峰命名
      words = key.replace(/([A-Z])/g, ' $1').trim().toLowerCase().split(' ');
    }

    // 常见英文单词对应的中文
    const wordMap = {
      'postal': '邮政',
      'code': '编码',
      'main': '主要',
      'products': '产品',
      'keywords': '关键词',
      'establishment': '成立',
      'year': '年份',
      'registered': '注册',
      'capital': '资本',
      'enterprise': '企业',
      'scale': '规模',
      'type': '类型',
      'trade': '贸易',
      'form': '形式',
      'exhibition': '展会',
      'history': '历史',
      'nature': '性质',
      'innovation': '创新',
      'award': '奖项',
      'cf': '广交会',
      'multi': '多次',
      'brand': '品牌',
      'exhibitor': '参展商',
      'time': '时间',
      'honored': '荣誉',
      'rural': '乡村',
      'revitalization': '振兴',
      'new': '新',
      'specialized': '专业',
      'green': '绿色',
      'customs': '海关',
      'certified': '认证',
      'high': '高',
      'tech': '科技',
      'session': '届次',
      'info': '信息',
      'web': '网络',
      'address': '地址',
      'url': '网址',
      'domain': '域名',
      'website': '网站',
      'company': '公司',
      'id': '编号',
      'status': '状态',
      'validation': '验证',
      'import': '导入',
      'business': '公司',
      'email': '邮箱'
    };

    // 翻译单词并组合成中文描述
    let chineseLabel = '';
    for (const word of words) {
      const lowercaseWord = word.toLowerCase();
      if (wordMap[lowercaseWord]) {
        chineseLabel += wordMap[lowercaseWord];
      } else {
        // 对于未知单词，保持原样
        chineseLabel += lowercaseWord;
      }
    }

    return chineseLabel || key;
  }
};

// 批量反查相关方法
// 文件选择变化
const handleFileChange = (file, fileListParam) => {
  selectedFile.value = file.raw;
  fileList.value = fileListParam;
};

// 文件超出限制
const handleExceed = () => {
  if (getCurrentLanguage() === 'zh') {
    ElMessage.warning('只能上传一个文件，请先移除已选文件');
  } else {
    ElMessage.warning('Only one file can be uploaded, please remove the selected file first');
  }
};

// 取消批量上传
const cancelBatchUpload = () => {
  if (batchUploading.value) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('反查正在进行中，请稍后再试');
    } else {
      ElMessage.warning('Reverse check is in progress, please try again later');
    }
    return;
  }
  
  showBatchDialog.value = false;
  selectedFile.value = null;
  fileList.value = [];
  uploadProgress.value = 0;
  uploadStatus.value = '';
  uploadStatusText.value = '';
};

// 提交批量反查
const submitBatchReverse = async () => {
  if (!selectedFile.value) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('请先选择要上传的Excel文件');
    } else {
      ElMessage.warning('Please select an Excel file to upload first');
    }
    return;
  }

  // 检查文件格式
  const fileName = selectedFile.value.name;
  if (!fileName.endsWith('.xlsx') && !fileName.endsWith('.xls')) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('文件格式不正确，只支持.xlsx和.xls格式');
    } else {
      ElMessage.error('Invalid file format, only .xlsx and .xls are supported');
    }
    return;
  }

  // 检查token
  const token = localStorage.getItem('token');
  if (!token) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('您尚未登录，请先登录');
    } else {
      ElMessage.warning('You are not logged in, please log in first');
    }
    router.push('/login');
    return;
  }

  // 准备FormData
  const formData = new FormData();
  formData.append('file', selectedFile.value);

  batchUploading.value = true;
  uploadProgress.value = 0;
  uploadStatus.value = '';
  
  if (getCurrentLanguage() === 'zh') {
    uploadStatusText.value = '正在上传文件...';
  } else {
    uploadStatusText.value = 'Uploading file...';
  }

  try {
    const response = await axios.post('/api/domain-lookup/batch', formData, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'multipart/form-data'
      },
      responseType: 'blob', // 重要：接收二进制数据
      timeout: 900000, // 15分钟超时（批量反查数据量大时需要更长时间）
      onUploadProgress: (progressEvent) => {
        // 上传进度
        if (progressEvent.total) {
          uploadProgress.value = Math.round((progressEvent.loaded * 50) / progressEvent.total);
        }
      },
      onDownloadProgress: (progressEvent) => {
        // 下载进度
        if (progressEvent.total) {
          const downloadProgress = Math.round((progressEvent.loaded * 50) / progressEvent.total);
          uploadProgress.value = 50 + downloadProgress;
        } else {
          uploadProgress.value = 75;
        }
        
        if (getCurrentLanguage() === 'zh') {
          uploadStatusText.value = '正在处理反查结果...';
        } else {
          uploadStatusText.value = 'Processing reverse check results...';
        }
      }
    });

    // 检查响应是否为错误JSON（而非Excel文件）
    if (response.data.type === 'application/json') {
      // 说明返回的是错误信息
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const errorData = JSON.parse(e.target.result);
          const errorMsg = errorData.msg || errorData.message || '批量反查失败';
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error(errorMsg);
          } else {
            ElMessage.error(errorData.msg || errorData.message || 'Batch reverse check failed');
          }
        } catch (parseError) {
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error('服务器返回了未知错误');
          } else {
            ElMessage.error('Server returned an unknown error');
          }
        }
      };
      reader.readAsText(response.data);
      
      uploadProgress.value = 0;
      uploadStatus.value = 'exception';
      if (getCurrentLanguage() === 'zh') {
        uploadStatusText.value = '反查失败';
      } else {
        uploadStatusText.value = 'Reverse check failed';
      }
      return;
    }

    // 成功接收到Excel文件，触发下载
    uploadProgress.value = 100;
    uploadStatus.value = 'success';
    if (getCurrentLanguage() === 'zh') {
      uploadStatusText.value = '反查完成，正在下载...';
    } else {
      uploadStatusText.value = 'Reverse check completed, downloading...';
    }
    
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    
    // 从响应头获取文件名，如果没有则使用默认名称
    const contentDisposition = response.headers['content-disposition'];
    let filename = `批量域名反查结果_${new Date().getTime()}.xlsx`;
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
      if (filenameMatch && filenameMatch[1]) {
        filename = decodeURIComponent(filenameMatch[1].replace(/['"]/g, ''));
      }
    }
    
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    if (getCurrentLanguage() === 'zh') {
      ElMessage.success('批量反查完成，结果已下载');
    } else {
      ElMessage.success('Batch reverse check completed, results downloaded');
    }
    
    // 重置状态
    setTimeout(() => {
      showBatchDialog.value = false;
      selectedFile.value = null;
      fileList.value = [];
      uploadProgress.value = 0;
      uploadStatus.value = '';
      uploadStatusText.value = '';
    }, 1500);

  } catch (error) {
    console.error('批量反查错误:', error);
    
    uploadProgress.value = 0;
    uploadStatus.value = 'exception';
    
    if (error.response) {
      // 服务器返回了错误
      if (error.response.status === 400) {
        // 尝试解析错误消息
        try {
          const errorBlob = error.response.data;
          const reader = new FileReader();
          reader.onload = (e) => {
            try {
              const errorData = JSON.parse(e.target.result);
              const errorMsg = errorData.msg || errorData.message || '批量反查失败';
              if (getCurrentLanguage() === 'zh') {
                ElMessage.error(errorMsg);
                uploadStatusText.value = errorMsg;
              } else {
                ElMessage.error(errorData.msg || errorData.message || 'Batch reverse check failed');
                uploadStatusText.value = errorData.msg || errorData.message || 'Reverse check failed';
              }
            } catch (parseError) {
              if (getCurrentLanguage() === 'zh') {
                ElMessage.error('批量反查失败，请检查文件格式');
                uploadStatusText.value = '反查失败';
              } else {
                ElMessage.error('Batch reverse check failed, please check file format');
                uploadStatusText.value = 'Reverse check failed';
              }
            }
          };
          reader.readAsText(errorBlob);
        } catch (e) {
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error('批量反查失败，请检查文件格式');
            uploadStatusText.value = '反查失败';
          } else {
            ElMessage.error('Batch reverse check failed, please check file format');
            uploadStatusText.value = 'Reverse check failed';
          }
        }
      } else {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error(`服务器错误 (${error.response.status})`);
          uploadStatusText.value = `服务器错误 (${error.response.status})`;
        } else {
          ElMessage.error(`Server error (${error.response.status})`);
          uploadStatusText.value = `Server error (${error.response.status})`;
        }
      }
    } else if (error.request) {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('服务器未响应，请检查网络连接');
        uploadStatusText.value = '服务器未响应';
      } else {
        ElMessage.error('No response from server, please check network');
        uploadStatusText.value = 'No server response';
      }
    } else {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('请求失败: ' + error.message);
        uploadStatusText.value = '请求失败';
      } else {
        ElMessage.error('Request failed: ' + error.message);
        uploadStatusText.value = 'Request failed';
      }
    }
  } finally {
    batchUploading.value = false;
  }
};

// 下载模板
const downloadTemplate = async () => {
  const lang = getCurrentLanguage();
  const token = localStorage.getItem('token');
  
  try {
    const response = await axios.get('/api/domain-lookup/batch/template', {
      params: { lang: lang },
      headers: {
        'Authorization': `Bearer ${token}`
      },
      responseType: 'blob'
    });
    
    const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    
    const fileName = lang === 'zh' ? '域名反查模板.xls' : 'Domain_Reverse_Template.xls';
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    if (lang === 'zh') {
      ElMessage.success('模板下载成功');
    } else {
      ElMessage.success('Template downloaded successfully');
    }
  } catch (error) {
    console.error('下载模板失败:', error);
    if (lang === 'zh') {
      ElMessage.error('模板下载失败，请稍后重试');
    } else {
      ElMessage.error('Template download failed, please try again later');
    }
  }
};
</script>

<style scoped>
.domain-reverse-check-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.main-container {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.content-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.search-content {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-header .title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.page-header .description {
  font-size: 14px;
  color: #606266;
}

.search-box {
  display: flex;
  margin-bottom: 24px;
}

.search-input {
  flex: 1;
}

.search-button {
  margin-left: 12px;
  min-width: 100px;
}

.api-error-alert {
  margin-bottom: 20px;
}

.search-results {
  background-color: white;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.results-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.result-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.result-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 16px;
  background-color: #fff;
  transition: box-shadow 0.3s;
}

.result-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.result-header {
  margin-bottom: 12px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  word-break: break-word;
}

.result-source {
  font-size: 12px;
  color: #909399;
  background-color: #f5f7fa;
  padding: 2px 8px;
  border-radius: 10px;
}

.info-row {
  display: flex;
  margin-bottom: 8px;
  align-items: flex-start;
  flex-wrap: wrap;
}

.info-label {
  min-width: 80px;
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
}

.info-value {
  flex: 1;
  color: #303133;
  word-break: break-word;
}

.highlight {
  color: #409eff;
  font-weight: 500;
}

.copy-btn {
  margin-left: 8px;
  padding: 2px 5px;
  height: 24px;
}

.no-results {
  margin-top: 40px;
  display: flex;
  justify-content: center;
}

.loading-container {
  margin-top: 20px;
}

.load-more {
  margin-top: 20px;
  text-align: center;
}

.feature-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  margin-top: 40px;
}

.feature-card {
  background-color: white;
  border-radius: 8px;
  padding: 24px;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;
}

.feature-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.feature-card .icon {
  margin-bottom: 16px;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #f5f7fa;
}

.blue-icon {
  color: #409eff;
}

.green-icon {
  color: #67c23a;
}

.purple-icon {
  color: #8e44ad;
}

.orange-icon {
  color: #e6a23c;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.card-desc {
  font-size: 14px;
  color: #606266;
  line-height: 1.4;
}

@media (max-width: 768px) {
  .result-cards {
    grid-template-columns: 1fr;
  }

  .feature-cards {
    grid-template-columns: 1fr;
  }

  .search-box {
    flex-direction: column;
  }

  .search-button {
    margin-left: 0;
    margin-top: 12px;
    width: 100%;
  }
}

/* 批量反查按钮样式 */
.batch-search-btn {
  margin-left: 10px;
}

/* 批量反查对话框样式 */
.batch-dialog-content {
  padding: 10px 0;
}

.batch-dialog-content p {
  margin: 8px 0;
  line-height: 1.6;
  font-size: 14px;
}

/* 上传组件样式优化 */
:deep(.el-upload-dragger) {
  padding: 40px 20px;
}

:deep(.el-icon--upload) {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 16px;
}

:deep(.el-upload__text) {
  font-size: 14px;
  color: #606266;
}

:deep(.el-upload__text em) {
  color: #409eff;
  font-style: normal;
}

:deep(.el-upload__tip) {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
}
</style> 
